12 use IBufferingStatsdDataFactory
;
13 use MediaWiki\Preferences\PreferencesFactory
;
14 use MediaWiki\Shell\CommandFactory
;
15 use MediaWiki\Storage\BlobStore
;
16 use MediaWiki\Storage\BlobStoreFactory
;
17 use MediaWiki\Storage\RevisionStore
;
18 use Wikimedia\Rdbms\LBFactory
;
20 use Wikimedia\Rdbms\LoadBalancer
;
21 use MediaHandlerFactory
;
22 use MediaWiki\Linker\LinkRenderer
;
23 use MediaWiki\Linker\LinkRendererFactory
;
24 use MediaWiki\Services\SalvageableService
;
25 use MediaWiki\Services\ServiceContainer
;
26 use MediaWiki\Services\NoSuchServiceException
;
34 use SearchEngineConfig
;
35 use SearchEngineFactory
;
38 use WatchedItemStoreInterface
;
39 use WatchedItemQueryService
;
43 use VirtualRESTServiceClient
;
44 use MediaWiki\Interwiki\InterwikiLookup
;
47 * Service locator for MediaWiki core services.
49 * This program is free software; you can redistribute it and/or modify
50 * it under the terms of the GNU General Public License as published by
51 * the Free Software Foundation; either version 2 of the License, or
52 * (at your option) any later version.
54 * This program is distributed in the hope that it will be useful,
55 * but WITHOUT ANY WARRANTY; without even the implied warranty of
56 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
57 * GNU General Public License for more details.
59 * You should have received a copy of the GNU General Public License along
60 * with this program; if not, write to the Free Software Foundation, Inc.,
61 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
62 * http://www.gnu.org/copyleft/gpl.html
70 * MediaWikiServices is the service locator for the application scope of MediaWiki.
71 * Its implemented as a simple configurable DI container.
72 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
73 * the network of service objects that defines MediaWiki's application logic.
74 * It acts as an entry point to MediaWiki's dependency injection mechanism.
76 * Services are defined in the "wiring" array passed to the constructor,
77 * or by calling defineService().
79 * @see docs/injection.txt for an overview of using dependency injection in the
80 * MediaWiki code base.
82 class MediaWikiServices
extends ServiceContainer
{
85 * @var MediaWikiServices|null
87 private static $instance = null;
90 * Returns the global default instance of the top level service locator.
94 * The default instance is initialized using the service instantiator functions
95 * defined in ServiceWiring.php.
97 * @note This should only be called by static functions! The instance returned here
98 * should not be passed around! Objects that need access to a service should have
99 * that service injected into the constructor, never a service locator!
101 * @return MediaWikiServices
103 public static function getInstance() {
104 if ( self
::$instance === null ) {
105 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
106 // but some information from the global scope has to be injected here,
107 // even if it's just a file name or database credentials to load
108 // configuration from.
109 $bootstrapConfig = new GlobalVarConfig();
110 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
113 return self
::$instance;
117 * Replaces the global MediaWikiServices instance.
121 * @note This is for use in PHPUnit tests only!
123 * @throws MWException if called outside of PHPUnit tests.
125 * @param MediaWikiServices $services The new MediaWikiServices object.
127 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
129 public static function forceGlobalInstance( MediaWikiServices
$services ) {
130 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
131 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
134 $old = self
::getInstance();
135 self
::$instance = $services;
141 * Creates a new instance of MediaWikiServices and sets it as the global default
142 * instance. getInstance() will return a different MediaWikiServices object
143 * after every call to resetGlobalInstance().
147 * @warning This should not be used during normal operation. It is intended for use
148 * when the configuration has changed significantly since bootstrap time, e.g.
149 * during the installation process or during testing.
151 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
152 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
153 * any of the services managed by MediaWikiServices exist. If any service objects
154 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
155 * with the operation of the services managed by the new MediaWikiServices.
156 * Operating with a mix of services created by the old and the new
157 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
158 * Any class implementing LAZY LOADING is especially prone to this problem,
159 * since instances would typically retain a reference to a storage layer service.
161 * @see forceGlobalInstance()
162 * @see resetGlobalInstance()
163 * @see resetBetweenTest()
165 * @param Config|null $bootstrapConfig The Config object to be registered as the
166 * 'BootstrapConfig' service. This has to contain at least the information
167 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
168 * config of the old instance of MediaWikiServices will be re-used. If there
169 * was no previous instance, a new GlobalVarConfig object will be used to
170 * bootstrap the services.
172 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
173 * See SalvageableService for details.
175 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
176 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
179 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
180 if ( self
::$instance === null ) {
181 // no global instance yet, nothing to reset
185 self
::failIfResetNotAllowed( __METHOD__
);
187 if ( $bootstrapConfig === null ) {
188 $bootstrapConfig = self
::$instance->getBootstrapConfig();
191 $oldInstance = self
::$instance;
193 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
194 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
196 if ( $quick === 'quick' ) {
197 self
::$instance->salvage( $oldInstance );
199 $oldInstance->destroy();
204 * Salvages the state of any salvageable service instances in $other.
206 * @note $other will have been destroyed when salvage() returns.
208 * @param MediaWikiServices $other
210 private function salvage( self
$other ) {
211 foreach ( $this->getServiceNames() as $name ) {
212 // The service could be new in the new instance and not registered in the
213 // other instance (e.g. an extension that was loaded after the instantiation of
214 // the other instance. Skip this service in this case. See T143974
216 $oldService = $other->peekService( $name );
217 } catch ( NoSuchServiceException
$e ) {
221 if ( $oldService instanceof SalvageableService
) {
222 /** @var SalvageableService $newService */
223 $newService = $this->getService( $name );
224 $newService->salvage( $oldService );
232 * Creates a new MediaWikiServices instance and initializes it according to the
233 * given $bootstrapConfig. In particular, all wiring files defined in the
234 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
236 * @param Config|null $bootstrapConfig The Config object to be registered as the
237 * 'BootstrapConfig' service.
239 * @param string $loadWiring set this to 'load' to load the wiring files specified
240 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
242 * @return MediaWikiServices
243 * @throws MWException
244 * @throws \FatalError
246 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
247 $instance = new self( $bootstrapConfig );
249 // Load the default wiring from the specified files.
250 if ( $loadWiring === 'load' ) {
251 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
252 $instance->loadWiringFiles( $wiringFiles );
255 // Provide a traditional hook point to allow extensions to configure services.
256 Hooks
::run( 'MediaWikiServices', [ $instance ] );
262 * Disables all storage layer services. After calling this, any attempt to access the
263 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
268 * @warning This is intended for extreme situations only and should never be used
269 * while serving normal web requests. Legitimate use cases for this method include
270 * the installation process. Test fixtures may also use this, if the fixture relies
273 * @see resetGlobalInstance()
274 * @see resetChildProcessServices()
276 public static function disableStorageBackend() {
277 // TODO: also disable some Caches, JobQueues, etc
278 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
279 $services = self
::getInstance();
281 foreach ( $destroy as $name ) {
282 $services->disableService( $name );
285 ObjectCache
::clear();
289 * Resets any services that may have become stale after a child process
290 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
291 * to call this method from the parent process.
295 * @note This is intended for use in the context of process forking only!
297 * @see resetGlobalInstance()
298 * @see disableStorageBackend()
300 public static function resetChildProcessServices() {
301 // NOTE: for now, just reset everything. Since we don't know the interdependencies
302 // between services, we can't do this more selectively at this time.
303 self
::resetGlobalInstance();
305 // Child, reseed because there is no bug in PHP:
306 // https://bugs.php.net/bug.php?id=42465
307 mt_srand( getmypid() );
311 * Resets the given service for testing purposes.
315 * @warning This is generally unsafe! Other services may still retain references
316 * to the stale service instance, leading to failures and inconsistencies. Subclasses
317 * may use this method to reset specific services under specific instances, but
318 * it should not be exposed to application logic.
320 * @note With proper dependency injection used throughout the codebase, this method
321 * should not be needed. It is provided to allow tests that pollute global service
322 * instances to clean up.
324 * @param string $name
325 * @param bool $destroy Whether the service instance should be destroyed if it exists.
326 * When set to false, any existing service instance will effectively be detached
327 * from the container.
329 * @throws MWException if called outside of PHPUnit tests.
331 public function resetServiceForTesting( $name, $destroy = true ) {
332 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
333 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
336 $this->resetService( $name, $destroy );
340 * Convenience method that throws an exception unless it is called during a phase in which
341 * resetting of global services is allowed. In general, services should not be reset
342 * individually, since that may introduce inconsistencies.
346 * This method will throw an exception if:
348 * - self::$resetInProgress is false (to allow all services to be reset together
349 * via resetGlobalInstance)
350 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
351 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
353 * This method is intended to be used to safeguard against accidentally resetting
354 * global service instances that are not yet managed by MediaWikiServices. It is
355 * defined here in the MediaWikiServices services class to have a central place
356 * for managing service bootstrapping and resetting.
358 * @param string $method the name of the caller method, as given by __METHOD__.
360 * @throws MWException if called outside bootstrap mode.
362 * @see resetGlobalInstance()
363 * @see forceGlobalInstance()
364 * @see disableStorageBackend()
366 public static function failIfResetNotAllowed( $method ) {
367 if ( !defined( 'MW_PHPUNIT_TEST' )
368 && !defined( 'MW_PARSER_TEST' )
369 && !defined( 'MEDIAWIKI_INSTALL' )
370 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
371 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
373 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
378 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
379 * This has to contain at least the information needed to set up the 'ConfigFactory'
382 public function __construct( Config
$config ) {
383 parent
::__construct();
385 // Register the given Config object as the bootstrap config service.
386 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
391 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
394 * Returns the Config object containing the bootstrap configuration.
395 * Bootstrap configuration would typically include database credentials
396 * and other information that may be needed before the ConfigFactory
397 * service can be instantiated.
399 * @note This should only be used during bootstrapping, in particular
400 * when creating the MainConfig service. Application logic should
401 * use getMainConfig() to get a Config instances.
406 public function getBootstrapConfig() {
407 return $this->getService( 'BootstrapConfig' );
412 * @return ConfigFactory
414 public function getConfigFactory() {
415 return $this->getService( 'ConfigFactory' );
419 * Returns the Config object that provides configuration for MediaWiki core.
420 * This may or may not be the same object that is returned by getBootstrapConfig().
425 public function getMainConfig() {
426 return $this->getService( 'MainConfig' );
433 public function getSiteLookup() {
434 return $this->getService( 'SiteLookup' );
441 public function getSiteStore() {
442 return $this->getService( 'SiteStore' );
447 * @return InterwikiLookup
449 public function getInterwikiLookup() {
450 return $this->getService( 'InterwikiLookup' );
455 * @return IBufferingStatsdDataFactory
457 public function getStatsdDataFactory() {
458 return $this->getService( 'StatsdDataFactory' );
463 * @return EventRelayerGroup
465 public function getEventRelayerGroup() {
466 return $this->getService( 'EventRelayerGroup' );
471 * @return SearchEngine
473 public function newSearchEngine() {
474 // New engine object every time, since they keep state
475 return $this->getService( 'SearchEngineFactory' )->create();
480 * @return SearchEngineFactory
482 public function getSearchEngineFactory() {
483 return $this->getService( 'SearchEngineFactory' );
488 * @return SearchEngineConfig
490 public function getSearchEngineConfig() {
491 return $this->getService( 'SearchEngineConfig' );
496 * @return SkinFactory
498 public function getSkinFactory() {
499 return $this->getService( 'SkinFactory' );
506 public function getDBLoadBalancerFactory() {
507 return $this->getService( 'DBLoadBalancerFactory' );
512 * @return LoadBalancer The main DB load balancer for the local wiki.
514 public function getDBLoadBalancer() {
515 return $this->getService( 'DBLoadBalancer' );
520 * @return WatchedItemStoreInterface
522 public function getWatchedItemStore() {
523 return $this->getService( 'WatchedItemStore' );
528 * @return WatchedItemQueryService
530 public function getWatchedItemQueryService() {
531 return $this->getService( 'WatchedItemQueryService' );
538 public function getCryptRand() {
539 return $this->getService( 'CryptRand' );
546 public function getCryptHKDF() {
547 return $this->getService( 'CryptHKDF' );
552 * @return MediaHandlerFactory
554 public function getMediaHandlerFactory() {
555 return $this->getService( 'MediaHandlerFactory' );
560 * @return MimeAnalyzer
562 public function getMimeAnalyzer() {
563 return $this->getService( 'MimeAnalyzer' );
568 * @return ProxyLookup
570 public function getProxyLookup() {
571 return $this->getService( 'ProxyLookup' );
578 public function getParser() {
579 return $this->getService( 'Parser' );
584 * @return ParserCache
586 public function getParserCache() {
587 return $this->getService( 'ParserCache' );
592 * @return GenderCache
594 public function getGenderCache() {
595 return $this->getService( 'GenderCache' );
602 public function getLinkCache() {
603 return $this->getService( 'LinkCache' );
608 * @return LinkRendererFactory
610 public function getLinkRendererFactory() {
611 return $this->getService( 'LinkRendererFactory' );
615 * LinkRenderer instance that can be used
616 * if no custom options are needed
619 * @return LinkRenderer
621 public function getLinkRenderer() {
622 return $this->getService( 'LinkRenderer' );
627 * @return TitleFormatter
629 public function getTitleFormatter() {
630 return $this->getService( 'TitleFormatter' );
635 * @return TitleParser
637 public function getTitleParser() {
638 return $this->getService( 'TitleParser' );
645 public function getMainObjectStash() {
646 return $this->getService( 'MainObjectStash' );
651 * @return \WANObjectCache
653 public function getMainWANObjectCache() {
654 return $this->getService( 'MainWANObjectCache' );
661 public function getLocalServerObjectCache() {
662 return $this->getService( 'LocalServerObjectCache' );
667 * @return VirtualRESTServiceClient
669 public function getVirtualRESTServiceClient() {
670 return $this->getService( 'VirtualRESTServiceClient' );
675 * @return \ConfiguredReadOnlyMode
677 public function getConfiguredReadOnlyMode() {
678 return $this->getService( 'ConfiguredReadOnlyMode' );
683 * @return \ReadOnlyMode
685 public function getReadOnlyMode() {
686 return $this->getService( 'ReadOnlyMode' );
691 * @return CommandFactory
693 public function getShellCommandFactory() {
694 return $this->getService( 'ShellCommandFactory' );
699 * @return \ExternalStoreFactory
701 public function getExternalStoreFactory() {
702 return $this->getService( 'ExternalStoreFactory' );
707 * @return BlobStoreFactory
709 public function getBlobStoreFactory() {
710 return $this->getService( 'BlobStoreFactory' );
717 public function getBlobStore() {
718 return $this->getService( '_SqlBlobStore' );
723 * @return RevisionStore
725 public function getRevisionStore() {
726 return $this->getService( 'RevisionStore' );
731 * @return PreferencesFactory
733 public function getPreferencesFactory() {
734 return $this->getService( 'PreferencesFactory' );
737 ///////////////////////////////////////////////////////////////////////////
738 // NOTE: When adding a service getter here, don't forget to add a test
739 // case for it in MediaWikiServicesTest::provideGetters() and in
740 // MediaWikiServicesTest::provideGetService()!
741 ///////////////////////////////////////////////////////////////////////////